from pyeasyaccept.result.Result import Result
from pyeasyaccept.commom.Configuration import Configuration

class ExpectCommand:
    """
    It executes the given command and checks
    whether the returned object, when converted to a string, yields the string
    given a first argument. If so, it returns a result with sucess message; otherwise, it returns 
    a result with an error message describing the error that was detected.
    
    The Expect command syntax is: 'expect result apCommand arg1 arg2 ... argN'
    
    @author: Gustavo Pereira
    """
    
    def execute(self, script, parsedLine):
        """
        This method executes the 'expect' command
        """        
        if(parsedLine.getNumberOfParameters() < 3):
            raise Exception("Expect command syntax is: 'expect result applicationCommand arg1 arg2 ... argN'")
        
        expectedResult = parsedLine.getParameter(1)
        apCommand = parsedLine.getParameter(2)
        
        if(self.hasParameters(parsedLine)):
            parameters = parsedLine.subLine(3)
        else:
            parameters = []
        
        try:
            appMethodResult = script.execute(apCommand, parameters)
        except Exception, e:
            exceptionMsg = str(e)
            result = Result(parsedLine, Configuration.ERROR_CODE, exceptionMsg)
            result.addException(None, exceptionMsg)
            return result
            

        if(expectedResult == str(appMethodResult)):
            return Result(parsedLine, Configuration.SUCCESS_CODE, appMethodResult)
        
        result = Result(parsedLine, Configuration.ERROR_CODE, str(appMethodResult))
        result.addException(None, "Was expected: " + str(expectedResult) + ", but got: " + str(appMethodResult))
        return result
        
    def hasParameters(self, parsedLine):
        """
        This method informs if a script line has parameters or not
        @param parsedLine: the script line
        """
        return parsedLine.getNumberOfParameters() > 3    
    
    def getParametersNames(self):
        return ["result"]    
    